//
//  TTOperation.m
//  Tint
//
//  Created by Kevin Wu on 2/22/12.
//  Copyright (c) 2012 Telligenty. All rights reserved.
//

#import "TTOperation.h"



@implementation TTOperation


TTSynthesizeDelegates(_delegates);



#pragma mark - Accessors

@synthesize error = _error;
@synthesize step = _step;




#pragma mark - Memory

- (id)init
{
    self = [super init];
    if ( self ) {
        _error = nil;
        _step = 0;
        
        _ready = NO;
        _executing = NO;
        _finished = NO;
        _cancelled = NO;
    }
    return self;
}

- (void)dealloc
{
    TTRelease(_error);
    _step = 0;
    
    _ready = NO;
    _executing = NO;
    _finished = NO;
    _cancelled = NO;
    
    [self destroyDelegates];
    
    [super dealloc];
}



#pragma mark - NSOperation

- (void)cancel
{
    if ( [self isCancelled] ) {
        return;
    }
    
    if ( [self isFinished] ) {
        return;
    }
    
    [self willChangeValueForKey:@"isCancelled"];
    _cancelled = YES;
    [self didChangeValueForKey:@"isCancelled"];
    
    [super cancel];
}

- (BOOL)isReady
{
    return ( (_ready) && [super isReady] );
}

- (BOOL)isExecuting
{
    return ( _executing );
}

- (BOOL)isFinished
{
    return ( _finished );
}

- (BOOL)isCancelled
{
    return _cancelled;
}

- (BOOL)isConcurrent
{
    return YES;
}



#pragma mark - Public

- (void)operationDidStart
{
    [[self delegates] makeObjectsRunSelectorOnMainThread:@selector(operationDidStart:) withObject:self];
}

- (void)operationUpdated
{
    [[self delegates] makeObjectsRunSelectorOnMainThread:@selector(operationUpdated:) withObject:self];
}

- (void)operationDidFailWithError:(NSError *)error
{
    [[self delegates] makeObjectsRunSelectorOnMainThread:@selector(operationDidFail:withError:) withObject:self withObject:error];
}

- (void)operationWillFinish
{
    [[self delegates] makeObjectsRunSelectorOnMainThread:@selector(operationWillFinish:) withObject:self];
}

- (void)operationDidFinish
{
    [[self delegates] makeObjectsRunSelectorOnMainThread:@selector(operationDidFinish:) withObject:self];
}

@end

